package com.test.demo.util;

import javafx.scene.layout.Region;
import javafx.scene.shape.SVGPath;
import org.apache.batik.parser.AWTPathProducer;
import org.apache.batik.parser.PathParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author guolinyuan
 */
public class SvgUtil {

    /**
     * 从SVG文件加载路径数据
     */
    public static Shape loadSVGPathFromFile(InputStream file) {
        try {
            // 使用DOM解析器读取SVG文件
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);
            // 获取所有<path>元素
            NodeList pathNodes = document.getElementsByTagName("path");

            java.util.List<Shape> paths = new ArrayList<>();
            for (int i = 0; i < pathNodes.getLength(); i++) {
                Element pathElement = (Element) pathNodes.item(i);

                String pathData = pathElement.getAttribute("d"); // 获取d属性（路径数据）

                Shape awtShape1 = createAWTShape(pathData);
                paths.add(awtShape1);
            }
            Shape awtShape = mergePaths(paths);
            return awtShape;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Shape createAWTShape(String pathData) {
        PathParser pathParser = new PathParser();
        AWTPathProducer awtPathProducer = new AWTPathProducer();
        pathParser.setPathHandler(awtPathProducer);
        pathParser.parse(pathData);
        return awtPathProducer.getShape();
    }

    // 合并多个 GeneralPath 为一个 Shape
    private static Shape mergePaths(List<Shape> paths) {
        GeneralPath mergedPath = new GeneralPath();

        for (Shape path : paths) {
            mergedPath.append(path, true);  // false 表示不连接路径
        }

        return mergedPath;
    }
}